import os
from flask import Flask

import time

from apps.ext import init_ext
from apps.user.url import user_api
from apps.basic.url import basic_api
from apps.test.url import test_api
from apps.bg.url import baogong_api

# 暂时不用
from setting import envs
import logging
from concurrent_log_handler import ConcurrentRotatingFileHandler
# 终端日志的输出格式
logging.basicConfig(format='%(asctime)s - %(levelname)s--->: %(message)s',
                    level=logging.DEBUG,
                    filemode='a')

def createLogFile(level):
    # 创建一个logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Log等级总开关

    # 创建一个handler，用于写入日志文件
    rq = time.strftime('%Y%m%d', time.localtime(time.time()))
    # log_date = rq[:10]
    log_path = os.getcwd() + '/Logs/'
    isExists = os.path.exists(log_path)
    # # 判断结果
    if not isExists:
        os.makedirs(log_path)
    log_name = os.getcwd() + '/Logs/{0}'.format(rq)  + '.log'
    # fh = logging.FileHandler(log_name, mode='a')
    fh = ConcurrentRotatingFileHandler(log_name, maxBytes=1024 * 20*200, backupCount=1000)
    fh.setLevel(level)  # 输出到file的log等级的开关

    # 定义handler的输出格式
    formatter = logging.Formatter("%(asctime)s - %(levelname)s--->: %(message)s")
    fh.setFormatter(formatter)
    logger.addHandler(fh)

def create_app(env):
    # app = Flask(__name__)
    PATH_ROOT = os.path.abspath(os.curdir)
    app = Flask(__name__,template_folder=PATH_ROOT+'\\templates',static_folder=PATH_ROOT+"\\templates/static")
    # 创建app实例前先配置好日志文件
    # setup_log()
    createLogFile('DEBUG')
    # 初始化配置
    app.config.from_object(envs.get("pro"))
    # 初始化SQLAlchemy
    init_ext(app)
    # 初始化路由
    user_api.init_app(app)
    basic_api.init_app(app)
    test_api.init_app(app)
    baogong_api.init_app(app)
    return app